﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class MainPanel : UIBase {

    public GameObject template;

    Transform main_gridpanel, detail_panel;
    detailPanelHolder detail_panel_holder;
    mainGridPanelHolder mainGridPanelHolder;
    List<PackageData> packageDatas;
    string currentSelectID;

    protected override void Start()
    {
        base.Start();

        //记录关键UI
        main_gridpanel = transform.Find("main_grid_panel");
        detail_panel = transform.Find("detail_panel");
        detail_panel_holder = detail_panel.GetComponentInChildren<detailPanelHolder>();
        mainGridPanelHolder = main_gridpanel.GetComponentInChildren<mainGridPanelHolder>();

        //初始化缩略图
        RefreshPackageGridView();

        //button
        detail_panel_holder.btn_save.onClick.AddListener(() =>
        {
            AppDataManager.Instance.SaveCurrentPackageInfo();
        });

        mainGridPanelHolder.btn_refreshList.onClick.AddListener(() =>
        {
            AppDataManager.Instance.RefrechPackagesInfo();
            RefreshPackageGridView();
        });

        //注册事件
        detail_panel_holder.inputfield_changeDur.onEndEdit.AddListener((value) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.changeDur = float.Parse(value);
            });
        });

        detail_panel_holder.inputField_fps.onEndEdit.AddListener((value) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.fps = int.Parse(value);
                Application.targetFrameRate = packdata.packageConfig.fps;
            });
        });

        detail_panel_holder.inputfield_alpha.onEndEdit.AddListener((value) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.winAlpha = int.Parse(value);
            });
        });

        detail_panel_holder.slider_scaletolorence.onValueChanged.AddListener((value) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.scaling_tolerance = value;
            });
        });

        detail_panel_holder.slider_totalscaletolorence.onValueChanged.AddListener((value) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.totalscaling_tolerance = value;
            });
        });


        detail_panel_holder.slider_width.onValueChanged.AddListener((value) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.winScalePercent = value;
            });
        });

        detail_panel_holder.slider_cameraOffsetX.onValueChanged.AddListener((value) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.camera_offsetX = value;
            });
        });

        detail_panel_holder.slider_cameraOffsetY.onValueChanged.AddListener((value) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.camera_offsetY = value;
            });
        });


        detail_panel_holder.slider_audioVisualStrengh.onValueChanged.AddListener((value) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.audioVisulStrengh = value;
            });
        });

        detail_panel_holder.toggle_isSupportAudioVisual.onValueChanged.AddListener((value) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.isSupportAudioVisual = value;
            });
        });

        detail_panel_holder.toggle_enbalefocus.onValueChanged.AddListener((value) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.focus_effect = value;
            });
        });

        detail_panel_holder.toggle_enable_douyin.onValueChanged.AddListener((value) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.isEnableDouYin = value;
            });
        });

        detail_panel_holder.toggle_transparentWhenHover.onValueChanged.AddListener((value) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.isTransparentWhenHover = value;
            });
        });

        detail_panel_holder.dropdown_checkMode.onValueChanged.AddListener((index) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.checkMode = (PaperManager.CheckMode)index;
            });
        });

        detail_panel_holder.dropdown_effecttype.onValueChanged.AddListener((index) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.effecttype = (EffectMgr.EffectType)index;
                EventBus.Instance.BroadCastEvent<EffectMgr.EffectType>(EventID.EffectChangeEvent, (EffectMgr.EffectType)index);
            });
        });

        detail_panel_holder.dropdown_fadeInType.onValueChanged.AddListener((index) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.fadeInType = (PaperManager.FadeInType)index;
            });
        });

        detail_panel_holder.dropdown_fadeOutType.onValueChanged.AddListener((index) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.fadeOutType = (PaperManager.FadeOutType)index;
            });
        });

        detail_panel_holder.dropdown_switchmode.onValueChanged.AddListener((index) =>
        {
            GetPackageData((packdata) =>
            {
                packdata.packageConfig.changeMode = (PaperManager.ItemChangeMode)index;
            });
        });

    }

    private void RefreshPackageGridView()
    {
        //销毁之前的
        Transform parent = template.transform.parent;
        for (int i = 0; i < parent.childCount; i++)
        {
            Transform child = parent.GetChild(i);
            if (child.gameObject != template)
            {
                Destroy(child.gameObject);
            }
        }

        //创建新的
        packageDatas = AppDataManager.Instance.PackageDatas;
        if (packageDatas.Count > 0)
        {
            for (int i = 0; i < packageDatas.Count; i++)
            {
                PackageData info = packageDatas[i];
                GameObject item = Instantiate<GameObject>(template, template.transform.parent);
                item.name = info.packageConfig.id;
                item.GetComponentInChildren<Text>().text = info.packageConfig.name;

                Utils.GetSafeComponet<Button>(item).onClick.AddListener(() =>
                {
                    OnButtonClick(item.name);
                    if(!detail_panel_holder.gameObject.activeInHierarchy)
                    {
                        detail_panel_holder.gameObject.SetActive(true);
                    }
                });

                string thumbnailTexPath = Path.Combine(info.packageDir, "Thumbnail.png");

                StartCoroutine(Res.LoadExternalTexture(thumbnailTexPath, (tex) =>
                {
                    Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
                    Transform transform1 = item.transform.Find("image");
                    Image image = transform1.GetComponent<Image>();
                    image.sprite = sprite;

                    //修正缩放
                    float hwradion = (float)tex.height / tex.width;
                    if (hwradion >= 1)
                    {
                        transform1.localScale = new Vector3(1f / hwradion, 1f, 1f);
                    }
                    else
                    {
                        transform1.localScale = new Vector3(1f, hwradion, 1f);
                    }

                    item.SetActive(true);

                }));
            }

            //默认选中第一个
            // OnButtonClick(packageDatas[0].packageConfig.id);
            detail_panel_holder.gameObject.SetActive(false);
        }
    }

    private void GetPackageData(Action<PackageData> callback)
    {
        if (!string.IsNullOrEmpty(currentSelectID))
        {
            PackageData packageData = AppDataManager.Instance.GetPackageInfo(currentSelectID);
            if (callback != null && packageData != null)
            {
                callback(packageData);
            }
        }
    }

    private void OnButtonClick(string id)
    {

        currentSelectID = id;
        PackageData packageData = AppDataManager.Instance.GetPackageInfo(id);

        PackageConfig packageConfig = packageData.packageConfig;

        detail_panel_holder.title.text = packageConfig.name;
        detail_panel_holder.dropdown_assettype.value = (int)packageConfig.assetType;
        detail_panel_holder.dropdown_catagory.value = (int)packageConfig.catagory;
        detail_panel_holder.dropdown_checkMode.value = (int)packageConfig.checkMode;
        detail_panel_holder.dropdown_fadeInType.value = (int)packageConfig.fadeInType;
        detail_panel_holder.dropdown_fadeOutType.value = (int)packageConfig.fadeOutType;
        detail_panel_holder.dropdown_switchmode.value = (int)packageConfig.changeMode;
        detail_panel_holder.toggle_isSupportAudioVisual.isOn = packageConfig.isSupportAudioVisual;
        detail_panel_holder.toggle_transparentWhenHover.isOn = packageConfig.isTransparentWhenHover;
        detail_panel_holder.toggle_enbalefocus.isOn = packageConfig.focus_effect;
        detail_panel_holder.toggle_enable_douyin.isOn = packageConfig.isEnableDouYin;
        detail_panel_holder.slider_audioVisualStrengh.value = packageConfig.audioVisulStrengh;
        detail_panel_holder.slider_width.value = packageConfig.winScalePercent;
        detail_panel_holder.slider_scaletolorence.value = packageConfig.scaling_tolerance;
        detail_panel_holder.slider_totalscaletolorence.value = packageConfig.totalscaling_tolerance;
        detail_panel_holder.slider_cameraOffsetX.value = packageConfig.camera_offsetX;
        detail_panel_holder.slider_cameraOffsetY.value = packageConfig.camera_offsetY;
        detail_panel_holder.inputfield_alpha.text = packageConfig.winAlpha.ToString();
        detail_panel_holder.inputField_fps.text = packageConfig.fps.ToString();
        detail_panel_holder.inputfield_changeDur.text = packageConfig.changeDur.ToString();

        //当资源类型是自定义时，不能切换特效
        if (packageConfig.assetType == PaperManager.AssetType.AssetBundle ||
            packageConfig.assetType == PaperManager.AssetType.SuperAssetBundle)
        {
            detail_panel_holder.dropdown_effecttype.enabled = false;
        }
        else
        {
            detail_panel_holder.dropdown_effecttype.value = (int)packageConfig.effecttype;
            detail_panel_holder.dropdown_effecttype.enabled = true;
        }

        EventBus.Instance.BroadCastEvent(EventID.LoadPackageEvent, id);

    }

    void Update () {
		
	}
}
